using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MonitorTemperatura.Entidades;
using MonitorTemperatura.Operciones;

namespace MonitorTemperatura.View.Reportes
{
    public partial class Reporte1 : System.Web.UI.Page
    {
        public DataSet LecturasDs
        {
            get { return (DataSet)Session["LecturasDs"]; }
            set { Session["LecturasDs"] = value; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!Page.IsPostBack)
            {
                LlenarGrid();
            }
        }
        private void LlenarGrid()
        {
            Hashtable ht = ObtenerMonitores();
            GetDataTable(ht);
            LecturasDs.DefaultViewManager.DataViewSettings[0].Sort = "IdLectura desc";
            LecturasGridView.DataSource = LecturasDs;
            LecturasGridView.DataMember = LecturasDs.Tables[0].TableName;
            LecturasGridView.DataBind();

        }

        private Hashtable ObtenerMonitores()
        {
            UbicacionOP op = new MonitorTemperatura.Operciones.UbicacionOP();
            Ubicacion ubicacion = new Ubicacion();
            if (Page.Request.QueryString != null)
                ubicacion.IdUbicacion = int.Parse((Request.QueryString["IdUbicacion"])??"0");
            return op.ObtenerUbicaciones(ubicacion);

        }

        private void GetDataTable(Hashtable ht)
        {
            DataTable t = new DataTable();
            
            DataColumn c1 = new DataColumn("IdLectura", typeof(int));
            DataColumn c2 = new DataColumn("Temperatura", typeof(string));
            DataColumn c3 = new DataColumn("Fecha", typeof(string));
            DataColumn c4 = new DataColumn("Hora", typeof(string));

            t.Columns.Add(c1);
            t.Columns.Add(c2);
            t.Columns.Add(c3);
            t.Columns.Add(c4);

            if (ht.Keys.Count > 0)
            {
                foreach (int key in ht.Keys)
                {

                    for (int k = 0; k < ((Ubicacion)ht[key]).Index;k++ )
                    {
                        Lectura li = ((Ubicacion) ht[key]).Lecturas[k];
                        DataRow r = t.NewRow();
                        r["IdLectura"] = li.idLectura;
                        r["Temperatura"] = li.Valor.ToString();
                        r["Fecha"] = li.Fecha.ToShortDateString();
                        r["Hora"] = li.Hora.ToShortTimeString();
                        t.Rows.Add(r);
                    }
                }
            }

            LecturasDs = new DataSet();
            LecturasDs.Tables.Add(t);
        }

       

    }
}
